﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugarWebApi.Jwt;

namespace SqlSugarWebApi.Controllers
{

    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class LoginController : ControllerBase
    {
        /// <summary>
        /// 获取Token
        /// </summary>
        /// <param name="rolename"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [HttpGet("Login")]
        [AllowAnonymous]
        public IActionResult Login(string rolename, string password)
        {
            string jwtStr = string.Empty;
            bool suc = false;

            if (rolename != null && password != null)
            {
                if (!rolename.EndsWith("Admin", StringComparison.CurrentCulture) || !password.EndsWith("123456", StringComparison.CurrentCulture))
                {
                    jwtStr = "输入不正确！";
                }
                else
                {
                    // 将用户id和角色名，作为单独的自定义变量封装进 token 字符串中。
                    TokenModel tokenModel = new TokenModel { Uid = "1", Role = rolename };
                    jwtStr = JwtHelper.IssueJwt(tokenModel);//登录，获取到一定规则的 Token 令牌
                    suc = true;
                }
            }
            else
            {
                jwtStr = "输入不能为空！";
            }

            return Ok(new
            {
                success = suc,
                token = jwtStr
            });
        }

        /// <summary>
        /// 解析Token
        /// </summary>
        /// <returns></returns>
        [HttpGet("ParseToken")]
        [Authorize]
        public IActionResult ParseToken()
        {
            //需要截取Bearer 
            var tokenHeader = HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
            if (string.IsNullOrWhiteSpace(tokenHeader))
                return Ok(new { message = "解析失败" });

            var user = JwtHelper.SerializeJwt(tokenHeader);
            return Ok(user);
        }
    }
}
